package ShareSubs;

# by lhtk : lhtk80t7@gmail.com
use strict;
use warnings;

use JSON qw/from_json to_json/;
use autodie qw/open close/;
use Bio::SeqIO;
use File::Copy;

use Mojo::Base 'Exporter';

our @EXPORT_OK = qw/get_conf json2href load_done update_done get_seq_href init_conf_file/;

# our $home_dir = $ENV{MOJO_HOME}; # mod_perl
# $home_dir = '.' unless (defined $home_dir and -d $home_dir);

# our $conf_file = join( '/', $home_dir, 'conf.json' );

# load json to hashref
sub json2href {
	my $fName = shift;
	my $href;

	my $fh;
	open $fh, '<', $fName;
	my $json_string = do { local $/; <$fh> };
	close $fh;

	$href = from_json($json_string);

	return $href;
}

# 获取配置信息
sub get_conf {

	# our $conf_file;
	my $conf_file = shift;
	return json2href($conf_file);
}

# load data from done.json
sub load_done {
	my ($jid,$data_dir) = @_; # $conf -- a hash ref
	# my ($jid,$conf) = @_; # $conf -- a hash ref
	# 免得反复加载

	# my $data_dir = join '/', $home_dir, $conf->{data_dir};

	my $done = {};
	my $done_fName = "$data_dir/$jid/done.json";
	if (-T $done_fName) {
		$done = json2href($done_fName);
	}

	return $done;
}

# 更新 done.json
sub update_done {

	# $done_info -- href
	# $conf -- href
	# my ($done_info,$jid,$conf) = @_;
	my ($done_info,$jid,$data_dir) = @_;

	# my $data_dir = join '/', $home_dir, $conf->{data_dir};

	my $done_fName = "$data_dir/$jid/done.json";

	my $fh;
	open $fh, '>', $done_fName;
	print $fh to_json($done_info, { pretty => 1 });
	close $fh;
}


sub get_seq_href {

	# my($jid,$conf) = @_;
	my($jid,$data_dir) = @_;

	# my $data_dir = join '/', $home_dir, $conf->{data_dir};
	my $in = Bio::SeqIO->new(-file => "$data_dir/$jid/input.fa", -format => 'Fasta');
	my %seqs;
	while (my $seq = $in->next_seq()) {
		my $id = $seq->id();
		my $dna = $seq->seq();
		my $len = $seq->length();

		#$dna =~ s/(\w{60})/$1\n/;
		$dna =~ s/(\w{100})/$1\n/g;
		chomp $dna;

		# $seqs{$id} = $dna;
		$seqs{$id} = [$dna, $len];
	}
	return \%seqs;
}

# 2019.1.25
# 初始的配置文件后缀为 .raw
sub init_conf_file {
	# 哪个服务
	my $f = shift;
	return 0 if (-e $f);

	my $raw = "$f.raw";
	die "$raw : not exists!" unless -e $raw;
	copy($raw, $f) or die "Copy failed: $!";

	return 0;
}

# ==============================
1;
